package com.zwj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwj.bo.RoleBo;
import com.zwj.dto.*;
import com.zwj.entity.*;
import com.zwj.enums.IsDeletedEnum;
import com.zwj.enums.SexEnum;
import com.zwj.enums.StatusEnum;
import com.zwj.mapper.*;
import com.zwj.service.SysRoleService;
import com.zwj.utils.DataCheckUtils;
import com.zwj.utils.DateUtils;
import com.zwj.utils.PaginationUtils;
import com.zwj.utils.TreeUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author zwj
 * @since 2021-09-13
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRoleEntity> implements SysRoleService {
    private final SysRoleMapper sysRoleMapper;
    private final UserMenuMapper userMenuMapper;
    private final SysMenuMapper sysMenuMapper;
    private final RoleMenuMapper roleMenuMapper;
    private final SysUserMapper sysUserMapper;
    private final UserRoleMapper userRoleMapper;
    public SysRoleServiceImpl(SysRoleMapper sysRoleMapper,SysMenuMapper sysMenuMapper,SysUserMapper sysUserMapper,RoleMenuMapper roleMenuMapper,UserRoleMapper userRoleMapper,UserMenuMapper userMenuMapper) {
        this.sysRoleMapper = sysRoleMapper;
        this.sysMenuMapper = sysMenuMapper;
        this.sysUserMapper = sysUserMapper;
        this.roleMenuMapper = roleMenuMapper;
        this.userRoleMapper = userRoleMapper;
        this.userMenuMapper = userMenuMapper;
    }
    @Override
    public Result selectRole(RoleBo roleBo) {
        //数据校验
        DataCheckUtils.isValid(PaginationUtils.isPagingParameters(roleBo.getNumber(), roleBo.getPage()), "分页参数错误!");
        int page = roleBo.getPage();
        roleBo.setPage(PaginationUtils.getPageIndex(roleBo.getPage(), roleBo.getNumber()));
        //查询项目组评分 mybatis
        List<Object> result = sysRoleMapper.selectRole(roleBo);
        int sum = ((List<Integer>) result.get(1)).get(0);
        //记录总数为0
        if (sum == 0) return Result.error().message("查询结果为空");
        PaginationDate paginationDate = PaginationUtils.getPaginationDate(roleBo.getNumber(), page, sum);
        //当前页大于总页数
        if (PaginationUtils.isValid(paginationDate))
            return Result.error().message("分页参数错误!");
        List<SysRoleEntity> sysUserEntities =  (List<SysRoleEntity>) result.get(0);
        return Result.ok().data(new ReturnDate(paginationDate,sysUserEntities ));
    }

    @Override
    public Result updateRoleStatus(RoleBo roleBo) {
        //数据校验
        DataCheckUtils.isNotBlank(roleBo.getId(), "角色Id不能为空!");
        DataCheckUtils.isNotBlank(roleBo.getStatus(), "用户状态不能为空!");
        DataCheckUtils.isValid(StatusEnum.getEnumValue(roleBo.getStatus()) != null, "角色状态不存在");
        QueryWrapper<SysRoleEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(SysRoleEntity::getId, roleBo.getId()).eq(SysRoleEntity::getIsDeleted, IsDeletedEnum.NO.getKey());
        SysRoleEntity role = sysRoleMapper.selectOne(sectionQueryWrapper);
        //查询结果校验
        if (role == null) {
            return Result.error().message("角色不存在！");
        }
        if (roleBo.equals(role.getStatus())) {
            return Result.error().message("用户状态不匹配不能修改");
        }
        SysRoleEntity updateStatus = new SysRoleEntity();
        updateStatus.setStatus(roleBo.getStatus());
        UpdateWrapper<SysRoleEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysRoleEntity::getId, roleBo.getId());
        int row = sysRoleMapper.update(updateStatus, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error().message("编辑角色状态失败");
        }
        return Result.ok();
    }

    @Override
    public Result deleteRole(RoleBo roleBo) {
        DataCheckUtils.isNotBlank(roleBo.getId(), "角色id不能为空!");
        QueryWrapper<SysRoleEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(SysRoleEntity::getId, roleBo.getId()).eq(SysRoleEntity::getIsDeleted, IsDeletedEnum.NO.getKey());
        SysRoleEntity role = sysRoleMapper.selectOne(sectionQueryWrapper);
        //查询结果校验
        if (role == null) {
            return Result.error().message("角色不存在！");
        }
        SysRoleEntity sysRoleEntity = new SysRoleEntity();
        sysRoleEntity.setIsDeleted(IsDeletedEnum.YES.getKey());
        UpdateWrapper<SysRoleEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysRoleEntity::getId, roleBo.getId()).eq(SysRoleEntity::getIsDeleted,IsDeletedEnum.NO.getKey());
        int row = sysRoleMapper.update(sysRoleEntity, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error().message("删除用户失败");
        }
        return Result.ok();
    }

    @Override
    public Result addRole(SysRoleEntity sysRoleEntity) {
        //数据校验
        //查询指定工号、身份证号、手机号是否重复
        //插入数据
        sysRoleEntity.setIsDeleted("0");
        sysRoleEntity.setCreateBy("1");
        sysRoleEntity.setCreateTime(DateUtils.getCurrentTime());
        int row = sysRoleMapper.insert(sysRoleEntity);
        //判断插入结果
        if (row == 0) {
            return Result.error().message("添加用户失败");
        }
        return Result.ok();
    }

    @Override
    public Result updateRole(SysRoleEntity sysRoleEntity) {
        UpdateWrapper<SysRoleEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysRoleEntity::getId, sysRoleEntity.getId());
        int row = sysRoleMapper.update(sysRoleEntity, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error().message("编辑角色信息失败");
        }
        return Result.ok();
    }

    @Override
    public Result updateRoleMenu(RoleBo roleBo) {
        QueryWrapper<RoleMenuEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RoleMenuEntity::getRoleId,roleBo.getId());
        roleMenuMapper.delete(wrapper);
        if(roleBo.getMenuIds()==null || roleBo.getMenuIds().equals("")){
            return Result.ok();
        }
        String[] menuIds = roleBo.getMenuIds().split(",");
        RoleMenuEntity roleMenuEntity = new RoleMenuEntity();
        roleMenuEntity.setRoleId(roleBo.getId());
        for(String menu:menuIds){
            roleMenuEntity.setMenuId(menu);
            roleMenuMapper.insert(roleMenuEntity);
        }
        return Result.ok();
    }

    @Override
    public Result selectRoleMenu(RoleBo roleBo) {
        SelectMenu selectMenu =  new SelectMenu();
        String menuIds =  sysMenuMapper.selectRoleMenu(roleBo.getId());
        selectMenu.setMenuIds(menuIds);
        List<SysMenu> menus = sysMenuMapper.selectMenu(selectMenu);
        if (menus.size() == 0) return Result.error().message("查询结果为空");
        return Result.ok().data(TreeUtils.createMenuTree(menus,"0"));
    }

    @Override
    public Result selectUserRole(RoleBo roleBo) {
        DataCheckUtils.isValid(PaginationUtils.isPagingParameters(roleBo.getNumber(), roleBo.getPage()), "分页参数错误!");
        int page = roleBo.getPage();
        roleBo.setPage(PaginationUtils.getPageIndex(roleBo.getPage(), roleBo.getNumber()));
        List<Object> result = null;
        if("0".equals(roleBo.getUserType())){
            result =  sysUserMapper.selectUserRole(roleBo);
        }else {
            String userIds =  userRoleMapper.selectUserRole(roleBo.getId());
            roleBo.setUserIds(userIds);
            result = sysUserMapper.selectUserRole1(roleBo);
        }
        int sum = ((List<Integer>) result.get(1)).get(0);
        //记录总数为0
        if (sum == 0) return Result.error().message("查询结果为空");
        PaginationDate paginationDate = PaginationUtils.getPaginationDate(roleBo.getNumber(), page, sum);
        //当前页大于总页数
        if (PaginationUtils.isValid(paginationDate))
            return Result.error().message("分页参数错误!");
        List<SysUserEntity> sysUserEntities =  (List<SysUserEntity>) result.get(0);
        for (SysUserEntity sysUserEntity:sysUserEntities){
            sysUserEntity.setSex(SexEnum.getEnumValue(sysUserEntity.getSex()));
            sysUserEntity.setStatus(StatusEnum.getEnumValue(sysUserEntity.getStatus()));
        }
        return Result.ok().data(new ReturnDate(paginationDate,sysUserEntities ));
    }

    @Override
    public Result cancelRoleUser(RoleBo roleBo) {
        QueryWrapper<UserRoleEntity> wrapper = new QueryWrapper<>();
        int result = 0;
        if("0".equals(roleBo.getUserType())){
            wrapper.lambda().eq(UserRoleEntity::getRoleId,roleBo.getId()).eq(UserRoleEntity::getUserId,roleBo.getUserId());
            result = userRoleMapper.delete(wrapper);
        }else {
            UserRoleEntity userRoleEntity = new UserRoleEntity();
            userRoleEntity.setRoleId(roleBo.getId());
            userRoleEntity.setUserId(roleBo.getUserId());
            result = userRoleMapper.insert(userRoleEntity);
        }
        //记录总数为0
        if (result == 0) return Result.error().message("操作失败");
        return Result.ok();
    }

    @Override
    public Result getMenu(String userID) {
        QueryWrapper<UserMenuEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(UserMenuEntity::getUserId, userID);
        List<UserMenuEntity> result = userMenuMapper.selectList(sectionQueryWrapper);
        if (result.size() == 0) {
            return Result.error().message("没有拥有权限的菜单！");
        }
        List<UserMenu> userMenus =  TreeUtils.getUserMenuTree(result,"0");
        return Result.ok().data(userMenus);
    }

    @Override
    public Result getRoles() {
        QueryWrapper<SysRoleEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(SysRoleEntity::getIsDeleted, IsDeletedEnum.NO).eq(SysRoleEntity::getStatus, StatusEnum.EFFECTIVE);
        List<SysRoleEntity> sysRoleEntities = sysRoleMapper.selectList(sectionQueryWrapper);
        if (sysRoleEntities.size() == 0) {
            return Result.error().message("没有有效角色");
        }
        List<EnumResult> result = sysRoleEntities.stream().map(
                entry -> new EnumResult(entry.getId(), entry.getName())).collect(Collectors.toList());
        return Result.ok().data(result);
    }
}
